<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <link rel="stylesheet" href="../../../component/pear/css/pear.css"/>
    <style>
        .layui-table .layui-input {
            text-align: center;
        }

        .editRowExt xm-select {
            min-height: 40px !important;
            line-height: 40px !important;
        }

        .editRowExt .layui-form-switch {
            top: 10px !important;
        }
        .query{
            display: none;
            padding: 0px 5px;
        }
    </style>
</head>
<body class="pear-container">
<div class="query">
    <form class="layui-form" action="">
        <div class="layui-row layui-col-space10">
            <div class="layui-col-md12">
                <div class="layui-card" style="margin-top: 10px;">
                    <div class="layui-card-header">用户名</div>
                    <div class="layui-card-body layui-row layui-col-space10">
                        <div class="layui-col-md12">
                            <input type="text" name="username" placeholder="账号" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-card" style="margin-top: 10px;">
                    <div class="layui-card-header">姓名</div>
                    <div class="layui-card-body layui-row layui-col-space10">
                        <div class="layui-col-md12">
                            <input type="text" name="nickname" placeholder="用户名" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-card" style="margin-top: 10px;">
                    <div class="layui-card-body layui-row layui-col-space10">
                        <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="user-query">
                            <i class="layui-icon layui-icon-search"></i>
                            查询
                        </button>
                        <button type="reset" class="pear-btn pear-btn-md">
                            <i class="layui-icon layui-icon-refresh"></i>
                            重置
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<div class="layui-card">
    <div class="layui-card-body userList">
        <table id="user-table" lay-filter="user-table"></table>
    </div>
</div>

<script type="text/html" id="user-toolbar">

    {{# if(d.isEdit==false || d.isEdit==undefined){ }}
    <button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="add">
        <i class="layui-icon layui-icon-add-1"></i>
        新增
    </button>
    <button class="pear-btn pear-btn-warming pear-btn-sm" lay-event="addSave">
        <i class="layui-icon layui-icon-delete"></i>
        保存
    </button>
    <button class="pear-btn pear-btn-normal pear-btn-sm" lay-event="edit">
        <i class="icon pear-icon pear-icon-edit"></i>
        编辑
    </button>
    <button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="batchRemove">
        <i class="layui-icon layui-icon-delete"></i>
        删除
    </button>
    {{# }else{ }}
    <button class="pear-btn pear-btn-warming pear-btn-sm" lay-event="save">
        <i class="layui-icon layui-icon-delete"></i>
        保存
    </button>
    <button class="pear-btn pear-btn-normal pear-btn-sm" lay-event="edit">
        <i class="icon pear-icon pear-icon-edit"></i>
        锁定
    </button>
    {{# } }}
    <button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="query">
        <i class="icon pear-icon pear-icon-search"></i>
        查询
    </button>
</script>

<script type="text/html" id="user-bar">
    {{# if(d.rowEdit == undefined){ }}
    <button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="remove"><i class="layui-icon layui-icon-delete"></i>
    </button>
    {{# } }}
</script>

<script type="text/html" id="user-status">
    {{#if (d.status == 0) { }}
    <span>锁定</span>
    {{# }else if(d.status == 1){ }}
    <span>启用</span>
    {{# } }}
</script>
<script type="text/html" id="user-sex">
    {{#if (d.sex == 1) { }}
    <span>男</span>
    {{# }else if(d.sex == 2){ }}
    <span>女</span>
    {{# } }}
</script>

<script type="text/html" id="user-login">
    {{#if (d.login == 0) { }}
    <span>在线</span>
    {{# }else if(d.sex == 1){ }}
    <span>离线</span>
    {{# } }}
</script>

<script type="text/html" id="user-createTime">
    {{layui.util.toDateString(d.createdate, 'yyyy-MM-dd HH:mm:ss')}}
</script>

<script src="../../../component/layui/layui.js"></script>
<script src="../../../component/pear/pear.js"></script>
<script>
    layui.use(['newTable', 'form', 'jquery', 'common', 'http', 'tableEdit', 'toast', 'popup', 'drawer'], function () {
        let table = layui.newTable;
        let form = layui.form;
        let $ = layui.jquery;
        let common = layui.common;
        var http = layui.http;
        var toast = layui.toast;
        var popup = layui.popup;
        var drawer = layui.drawer;
        var tableEdit = layui.tableEdit;

        let MODULE_PATH = "/service-adminManage/organization/sysUser/";

        let cols = [
            [{
                type: 'numbers', fixed: "left"
            }, {
                type: 'checkbox', fixed: "left"
            },
                {
                    title: '账号',
                    field: 'username',
                    align: 'center',
                    width: 150,
                    editRow: function (data) {
                        if (data.add) {
                            return "customer";
                        } else {
                            return undefined;
                        }
                    },
                    verify: function (data) {
                        if (data.add) {
                            return {
                                required: true
                                , reg: {
                                    expression: /^[a-zA-Z]\w{5,31}$/, msg: "必须是以字母开头，长度在6~32之间，只能包含字符、数字和下划线"
                                }
                            }
                        } else {
                            return {};
                        }
                    }
                },
                {
                    title: '姓名',
                    field: 'nickname',
                    align: 'center',
                    editRow: "customer",
                    verify: {
                        required: true,
                        size: {
                            min: 1, max: 255
                        }
                    }

                },
                {
                    title: '性别',
                    field: 'sex',
                    align: 'center',
                    width: 100,
                    templet: '#user-sex',
                    editRow: "select",
                    option: {
                        data: [
                            {
                                "name": "男", "value": 1
                            },
                            {
                                "name": "女", "value": 2

                            }]
                    },
                    verify: {
                        required: true
                    }
                },
                {
                    title: '电话',
                    field: 'telephone',
                    align: 'center',
                    editRow: "customer",
                    verify: {
                        telephone: true
                    }
                },
                {
                    title: '邮箱',
                    field: 'email',
                    align: 'center',
                    editRow: "customer",
                    verify: {
                        email: true
                    }
                },
                {
                    title: '启用',
                    field: 'status',
                    align: 'center',
                    templet: '#user-status',
                    editRow: "switch"
                },
                {
                    title: '登录',
                    field: 'login',
                    align: 'center',
                    templet: '#user-login',
                    hide: true
                },
                {
                    title: '注册时间',
                    field: 'createTime',
                    align: 'center',
                    templet: '#user-createTime'
                },
                {
                    title: '操作',
                    toolbar: '#user-bar',
                    align: 'center',
                    width: 130,
                    field: "userBar",
                    editRow: "render" //重载
                }
            ]
        ]

        var userTable = table.render({
            contentType:"application/x-www-form-urlencoded",
            height: 'full-80',
            elem: '#user-table',
            url: MODULE_PATH+'getList',
            page: true,
            cols: cols,
            skin: 'grid',
            method: 'post',
            toolbar: '#user-toolbar',
            limit: 10,
            limits: [10],
            request: {
                pageName: 'page' //页码的参数名称，默认：page
                , limitName: 'limit' //每页数据量的参数名，默认：limit
            },
            headers: {
                "authorization": http.ajax.getToken()
            },
            defaultToolbar: ['filter', 'print', 'exports']
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            }
            , response: {
                statusCode: 200 //规定成功的状态码，默认：0
            },
            done: function (res, curr, count) {
                if (this.isEdit == false || this.isEdit == undefined) {

                } else {
                    var op = {
                        tableId: "user-table",
                        tableObj: userTable,
                        addEmptyRow: false,
                        emptyRowData: {}
                    }
                }
                tableEdit.render(op);
            }
        });


        table.on('tool(user-table)', function (obj) {
            if (obj.event === 'remove') {
                window.remove(obj);
            } else if (obj.event === 'edit') {
                window.edit(obj);
            }
        });

        table.on('toolbar(user-table)', function (obj) {
            if (obj.event === 'add') {
                window.add();
            } else if (obj.event === 'refresh') {
                window.refresh();
            } else if (obj.event === 'query') {
                drawer.open({
                    direction: "right",
                    dom: ".query",
                    distance: "30%"
                });
            } else if (obj.event === 'edit') {
                if ($(this).html().indexOf("编辑") != -1) {
                    userTable = table.reload("user-table", {
                        isEdit: true
                    }, true)
                } else {
                    userTable = table.reload("user-table", {
                        isEdit: false
                    }, true)
                }
            } else if (obj.event === 'save') {
                var isError = tableEdit.verifyData(userTable);
                if (isError) {
                    //提交数据
                    console.log("等待提交数据！");
                    //拆分数据
                    let allData = layui.newTable.cache["user-table"];
                    let addData = [];
                    let updateData = [];
                    $.each(allData, function (index, item) {
                        if (item.add == undefined) {
                            let info = $.extend({}, item);
                            delete info.username
                            delete info.password
                            updateData.push(info);
                        } else {
                            let info = $.extend({}, item);
                            info["password"] = "123456";
                            addData.push(info);
                        }
                    })

                    layer.confirm('确定保存修改么', {
                        icon: 3,
                        title: '提示'
                    }, function (index) {
                        layer.close(index);
                        let loading = layer.load();
                        http.ajax({
                            url: MODULE_PATH+"/update",
                            dataType: 'json',
                            type: 'post',
                            data: JSON.stringify(updateData),
                            contentType: "application/json",
                            success: function (result) {
                                layer.close(loading);
                                if (result.status == 200) {
                                    toast.success({title: '保存用户信息',message: '保存成功'})
                                } else {
                                    if (result.status == 10001) {
                                        //验证错误
                                        tableEdit.serverError(userTable, result.msg);
                                        userTable = table.reload("user-table", {
                                        }, true)
                                    } else {
                                        toast.error({title: '保存用户信息',message: result.msg})
                                    }
                                }
                            },
                            error: function (res) {
                                layer.close(loading);
                            }
                        })
                    });
                }
            } else if (obj.event === 'addSave') {
                var isError = tableEdit.verifyData(userTable);
                if (isError) {
                    //提交数据
                    console.log("等待提交数据！");
                    //拆分数据
                    let allData = layui.newTable.cache["user-table"];
                    let addData = [];
                    let updateData = [];
                    $.each(allData, function (index, item) {
                        if (item.add == undefined) {
                            let info = $.extend({}, item);
                            delete info.username
                            delete info.password
                            updateData.push(info);
                        } else {
                            let info = $.extend({}, item);
                            info["password"] = "abcd1234";
                            addData.push(info);
                        }
                    })

                    if (addData.length == 0) {
                        popup.failure("没有新增的数据需要保存！")
                        return
                    }

                    layer.confirm('确定保存数据么', {
                        icon: 3,
                        title: '提示'
                    }, function (index) {
                        layer.close(index);
                        let loading = layer.load();
                        http.ajax({
                            url: MODULE_PATH+"save",
                            dataType: 'json',
                            type: 'post',
                            data: JSON.stringify(addData),
                            contentType: "application/json",
                            success: function (result) {
                                layer.close(loading);
                                if (result.status == 200) {
                                    // toast.success({title: '提示',message: '保存成功',position: 'topRight'})
                                    toast.success({title: '保存用户信息',message: '保存成功'})
                                    userTable = table.reload("user-table", {
                                    }, true)
                                } else {
                                    if (result.status == 10001) {
                                        //验证错误
                                        tableEdit.serverError(userTable, result.msg);
                                    } else {
                                        toast.error({title: '保存用户信息',message: result.msg})
                                    }
                                }
                            },
                            error: function (res) {
                                layer.close(loading);
                            }
                        })
                    });
                }
            } else if (obj.event === 'batchRemove') {
                window.batchRemove(obj);
            }
        });

        form.on('submit(user-query)', function (data) {
            userTable = table.reload("user-table", {
                where: data.field
            }, true)
            return false;
        });

        form.on('switch(user-enable)', function (obj) {
            layer.tips(this.value + ' ' + this.name + '：' + obj.elem.checked, obj.othis);
        });

        window.add = function () {
            //追加一行
            userTable.addRow({status: 1});
            var rowNum = table.cache["user-table"].length;
            var op = {
                tableId: "user-table",
                tableObj: userTable,
                addEmptyRow: false,
                emptyRowData: {},
                rowNum: rowNum,
            }
            tableEdit.render(op);
            //表格滚到最底部
            let $table = $('[lay-id="user-table"] .layui-table-main')[0];
            $table.scrollTop = $table.scrollHeight;
        }

        window.remove = function (obj) {
            layer.confirm('确定要删除该用户', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                http.ajax({
                    url: MODULE_PATH+"del",
                    dataType: 'json',
                    type: 'post',
                    data: {
                        ids: obj.data.id
                    },
                    contentType: "application/x-www-form-urlencoded",
                    success: function (result) {
                        layer.close(loading);
                        if (result.status == 200) {
                            toast.success({title: '删除用户信息',message: '删除成功'})
                            $("[lay-filter='user-query']").click()
                        } else {
                            toast.error({title: '删除用户信息',message: msg})
                        }
                    },
                    error: function (res) {
                        layer.close(loading);
                    }
                })
            });
        }

        window.batchRemove = function (obj) {

            let data = table.checkStatus(obj.config.id).data;
            var checkIds = [];

            if (data.length == 0) {
                layer.msg("未选中数据", {
                    icon: 3,
                    time: 1000
                });
                return false;
            }

            for (let datum of data) {
                checkIds.push(datum.id);
            }

            layer.confirm('确定要删除这些用户', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                http.ajax({
                    url: MODULE_PATH+"del",
                    dataType: 'json',
                    type: 'post',
                    data: {
                        ids: checkIds.join(",")
                    },
                    contentType: "application/x-www-form-urlencoded",
                    success: function (result) {
                        layer.close(loading);
                        if (result.status == 200) {
                            toast.success({title: '删除用户信息',message: '删除成功'})
                            $("[lay-filter='user-query']").click()
                        } else {
                            toast.error({title: '删除用户信息',message: msg})
                        }
                    },
                    error: function (res) {
                        layer.close(loading);
                    }
                })
            });
        }

        window.refresh = function (param) {
            table.reload('user-table');
        }
    })
</script>
</body>
</html>
